package com.lilanz.facepass.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lilanz.facepass.dao.ClientMapper;
import com.lilanz.facepass.entity.client.Client;
import com.lilanz.facepass.service.IClientService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> implements IClientService {
    @Resource
    private ClientMapper clientMapper;

    @Resource
    private HTTPServiceImpl httpService;


    /**
     * 查出client信息   并判断是否更新token
     *
     * @return
     */
    @Override
    public Client selectClient() {
        Client client = clientMapper.selectOne();
        Date tokenEffectiveDate = client.getTokenEffectiveDate();
        //访问token过期了,重新生成访问token
        if (new Date().getTime() > tokenEffectiveDate.getTime()) {
            Map<String, String> map = new HashMap<>();
            map.put("clientId", client.getClientId());
            map.put("refreshToken", client.getRefreshToken());
            map.put("grantType", client.getGrantType());
            httpService.updateToken(map);
            return clientMapper.selectOne();
        }
        return client;
    }


    /**
     * 查出client信息   不判断是否更新token
     *
     * @return
     */
    @Override
    public Client selectOne() {
        return clientMapper.selectOne();
    }


    /**
     * 更新不为空的字段
     *
     * @return
     */
    @Override
    @Transactional
    public int updateByClientId(Client client) {
        EntityWrapper<Client> clientEntityWrapper = new EntityWrapper<>();
        clientEntityWrapper.eq("clientId", client.getClientId());
        return clientMapper.update(client, clientEntityWrapper);
    }
}
